<template>
    <el-container>
      <el-header>书架</el-header>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="8" v-for="book in books" :key="book.idbook">
            <el-card>
              <h3 @click="viewBook(book.idbook)">{{ book.bookName }}</h3>
              <p>作者: {{ book.author }}</p>
              <p>点击次数: {{ book.clicks }}</p>
              <el-button type="danger" @click="removeFromBookshelf(book.idbook)">移出书架</el-button>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        books: []
      };
    },
    created() {
      this.fetchBookshelf();
    },
    methods: {
      fetchBookshelf() {
        const iduser = this.$store.state.user.iduser; // 假设你在 Vuex 中存储了用户信息
        axios.get(`/api/bookshelf/${iduser}`)
          .then(response => {
            const bookshelf = response.data;
            const bookIds = bookshelf.map(item => item.idbook);
            this.fetchBooks(bookIds);
          })
          .catch(error => {
            console.error('获取书架失败:', error);
          });
      },
      fetchBooks(bookIds) {
        axios.post('/api/books/batch', bookIds)
          .then(response => {
            this.books = response.data;
          })
          .catch(error => {
            console.error('获取书籍信息失败:', error);
          });
      },
      viewBook(idbook) {
        this.$router.push({ path: `/read/${idbook}` });
      },
      removeFromBookshelf(idbook) {
        const iduser = this.$store.state.user.iduser; // 假设你在 Vuex 中存储了用户信息
        axios.delete('/api/bookshelf', { params: { iduser, idbook } })
          .then(response => {
            this.books = this.books.filter(book => book.idbook !== idbook);
            this.$message.success('已移出书架');
          })
          .catch(error => {
            console.error('移出书架失败:', error);
            this.$message.error('移出书架失败');
          });
      }
    }
  };
  </script>
  
  <style scoped>
  h3 {
    cursor: pointer;
    color: #409EFF;
  }
  h3:hover {
    text-decoration: underline;
  }
  </style>
  